import {
  isObject,
  isPromise,
  isFunction,
  getRootScrollTop,
  setRootScrollTop
} from "../utils/index.mjs";
// 检测是否为空
function isEmptyValue(value) {
  if (Array.isArray(value)) {
    return !value.length;
  }
  if (value === 0) {
    return false;
  }
  return !value;
}
/* 
  require 是否为必须字段 boolean
  message  错误提示文案 string | (value, rule) => string
  validator 通过函数进行校验 (value, rule) => boolean | Promise
  pattern 通过正则表达式进行校验 RegExp
  trigger 本项规则的触发时机, 可选值 onChange onBlur string
  formatter 格式化函数, 将表单项的值转换后进行校验
  validateEmpty 是否要为空做校验
*/

// 同步验证 pattern
function runSyncRule(value, rule) {
  if (isEmptyValue(value)) {
    if (rule.required) {
      return false;
    }
    if (rule.validateEmpty === false) {
      return true;
    }
  }
  if (rule.pattern && !rule.pattern.test(String(value))) {
    return false;
  }
  return true;
}

// validator同步或异步验证
function runRuleValidator(value, rule) {
  return new Promise((resolve) => {
    const returnVal = rule.validator(value, rule);
    if (isPromise(returnVal)) {
      // validator返回值为promise  通过true(resolve)默认返回
      returnVal.then(resolve);
      return;
    }
    resolve(returnVal);
  });
}

// 获取验证提示信息
function getRuleMessage(value, rule) {
  const { message } = rule;
  if (isFunction(message)) {
    return message(value, rule);
  }
  return message || "";
}

// 输入法事件设定composing状态
function startComposing({ target }) {
  target.composing = true;
}

// 输入完后手动触发input事件
function endComposing({ target }) {
  if (target.composing) {
    target.composing = false;
    target.dispatchEvent(new Event("input"));
  }
}

// 是否自适应内容高度,只对 textarea有效, 可传入对象, 如{maxHeight: 100, minHeight: 50} 单位为px
function resizeTextarea(input, autosize) {
  // 记录之前的滚动高度
  const scrollTop = getRootScrollTop();
  input.style.height = "auto";
  let height = input.scrollHeight;
  if (isObject(autosize)) {
    const { maxHeight, minHeight } = autosize;
    if (maxHeight !== void 0) {
      height = Math.min(height, maxHeight);
    }
    if (minHeight !== void 0) {
      height = Math.max(height, minHeight);
    }
  }
  if (height) {
    input.style.height = `${height}px`;
    setRootScrollTop(scrollTop);
  }
}

// 控制键盘弹出的类型
function mapInputType(type) {
  if (type === "number") {
    return {
      type: "text",
      inputmode: "decimal" // 允许小数
    };
  }
  if (type === "digit") {
    return {
      type: "tel",
      inputmode: "numeric" // 整数
    };
  }
  return { type };
}

function getStringLength(str) {
  return [...str].length;
}

function cutString(str, maxlength) {
  return [...str].slice(0, maxlength).join("");
}
export {
  cutString,
  endComposing,
  getRuleMessage,
  getStringLength,
  isEmptyValue,
  mapInputType,
  resizeTextarea,
  runRuleValidator,
  runSyncRule,
  startComposing
};
